# app/db/session.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
from sqlalchemy_utils import create_database, database_exists
# 从正确的位置导入 Base 和所有模型
from app.models.models import Base, User, Video, Voice, Job, InternalUser, InternalVideo, InternalVoice, InternalJob

DATABASE_URL = (
    f"mysql+pymysql://{settings.MYSQL_USER}:{settings.MYSQL_PASSWORD}"
    f"@{settings.MYSQL_HOST}:{settings.MYSQL_PORT}/{settings.MYSQL_DB}?charset=utf8mb4"
)

# 检查数据库是否存在
if not database_exists(DATABASE_URL):
    create_database(DATABASE_URL)
    print("数据库不存在，已创建数据库")

engine = create_engine(DATABASE_URL, echo=False, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建所有数据库表
Base.metadata.create_all(bind=engine)

# 依赖注入的数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
        
def get_db_session():
    """
    获取一个新的数据库会话，用于在异步任务中使用。
    """
    db = SessionLocal()
    return db
